package features.advance.mybatis;

import features.advance.mybatis.dao.Test;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.CacheNamespaceRef;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @author LIN
 * @date 2021-07-06
 * Mybatis 是半ORM框架
 * MyBatis 是一款优秀的持久层框架，它支持自定义 SQL、存储过程以及高级映射。
 * MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
 * MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、
 * 接口和 Java POJO（Plain Old Java Objects，普通老式 Java 对象）为数据库中的记录。
 */
@Slf4j
public class MybatisDemo {

    @CacheNamespaceRef(name = "features.advance.mybatis.dao.Test")
    interface DemoMapper{

        @Select(value = {
                "select * ",
                "from ",
                " pdccocartype"
        })
        List<Map<String,Object>> selectAll();
    }

    public static void main(String[] args) {
        try {
//            jdbc();
            mybatis();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static void mybatis() {
        // 编程式进行数据查询
        String resource = "mapper/MapperConfig.xml";
        SqlSession sqlSession = null;
        SqlSession sqlSession1 = null;
        try (Reader resourceAsReader = Resources.getResourceAsReader(resource)) {
            Properties properties = new Properties();
            properties.setProperty("driver","com.mysql.cj.jdbc.Driver");
            properties.setProperty("url","jdbc:mysql://localhost:3306/erpcg_pd?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8");
            properties.setProperty("username","root");
            SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsReader,properties);
            sqlSession = build.openSession();
            sqlSession.getConfiguration().addMapper(DemoMapper.class);

            DemoMapper mapper2 = sqlSession.getMapper(DemoMapper.class);
            System.out.println("注解式查询select");
            List<Map<String, Object>> maps = mapper2.selectAll();
            Test mapper = sqlSession.getMapper(Test.class);
            List<String> objects = mapper.selectIds(1);
//            List<Object> objects = sqlSession.selectList("selectIds");
            log.debug("查询到的数据：{}",objects);
            objects = mapper.selectIds(1);
            log.debug("查询到的数据：{}",objects);
            sqlSession.commit();
            sqlSession1 = build.openSession();
            Test mapper1 = sqlSession1.getMapper(Test.class);
            List<String> strings = mapper1.selectIds(1);
            log.debug("查询到的数据：{}",strings);


        }catch (Exception e){
            log.error(e.getMessage());
            e.printStackTrace();
        }finally {
            if(sqlSession!=null){
                sqlSession.close();
            }
            if(sqlSession1!=null){
                sqlSession1.close();
            }
        }
    }

    public static void jdbc() throws ClassNotFoundException {
        String fileName =
                "D:\\project-2022\\yqjr\\doc\\sql\\UAT_MID-USER-MU_DEALER_20220503 - copy.sql";
        File sqlFile = new File(fileName);
        List<String> list = new ArrayList<>();
        try(FileReader fileReader = new FileReader(sqlFile);BufferedReader br = new BufferedReader(fileReader);){
            String s = null;
            while (null != (s = br.readLine())){
                if(!s.isEmpty()){
                    list.add(s.replaceAll(";",""));
                }
            }

        }catch(Exception e){
            log.debug(e.getMessage());
        }

        String url = "jdbc:oracle:thin:@10.20.195.60:1521:afhxsit";
        String userName = "mid_prod";
        String password = "mid_prod";
        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection connection = null;
        try{

            connection = DriverManager.getConnection(url,userName,password);

            Statement statement = connection.createStatement();

            for (int i = 0; i < list.size(); i++) {
//                statement.addBatch(list.get(i));

                if(i % 10 == 0 && i > 0){
//                    statement.clearBatch();
                }
            }
            connection.commit();
        }catch(Exception e){
            log.debug(e.getMessage());
            try {
                if(connection != null){
                    connection.rollback();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }finally {
            try {
                if(connection != null){
                    connection.close();
                }

            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }

}
